import fileCacheService from './fileCacheService.js'

/**
 * 图片缓存key
 */
const _IMAGE_CACHE_KEY = '_IMAGE_CACHE_KEY_';

/**
 * 图片缓存对象
 */
let _IMAGE_CACHE_MAP_ = null;

/**
 * 初始化
 */
const init = () => {
	const expiration = 8;
	_IMAGE_CACHE_MAP_ = fileCacheService.init({
		key: _IMAGE_CACHE_KEY,
		expiration
	});
}

/**
 * 获取图片url
 * @param {String} picId 图片唯一标识
 */
const getCachedImageUrl = (picId) => {
	if (_IMAGE_CACHE_MAP_[picId]) {
		return _IMAGE_CACHE_MAP_[picId];
	}
	return null;
}

/**
 * 通过图片ID获取图片链接
 * @param {String} picId   图片名称
 * @param {String} picUrl  图片URL
 */
const getImageSrcByPicId = (picId, picUrl) => {
	return new Promise((resolve, reject) => {
		if (picId && picUrl) {
			let filePath = fileCacheService.getCacheFilePath(picId);
			if (!filePath) {
				fileCacheService.saveFile(picId, picUrl).then((savedFilePath) => {
					resolve(savedFilePath);
				}, () => {
					reject();
				});
				return;
			} else {
				fileCacheService.touchFile(picId);
				resolve(filePath);
				return;
			}
		}
		reject();
	})
}

export default {
	init,
	getImageSrcByPicId
}
